//跟进统计表
var $dataInfo = $('#followStatisticsTable');
//防止表头与表格不对齐
$(window).resize(function () {
    $dataInfo.bootstrapTable('resetView');
});

$(function () {
    //时间控件初始化
    timeComponentInit();

    //初始化跟进统计表
    followStatisticsByAdmin();

    polyLineInitDataByAdmin();//折线图数据初始化
    numPieInitDataByAdmin();//总跟进次数饼状图数据初始化
    statusPieInitDateByAdmin("process", 0)

    $('#followStatisticsTable').on('click-row.bs.table', function (e, row, $element, field) {
        $element.addClass('active-row').siblings('tr').removeClass('active-row');
    })
})


function timeComponentInit() {
    var endTime = new Date().FormatFMT("yyyy-MM")
    var startTime = GetPreMonthDay(new Date().FormatFMT("yyyy-MM"), 6)
    $('#startTm').datetimepicker({
        format: 'YYYY-MM',
        locale: moment.locale('zh-cn'),
        defaultDate: startTime
    });
    $('#endTm').datetimepicker({
        format: 'YYYY-MM',
        locale: moment.locale('zh-cn'),
        defaultDate: endTime
    });
}


//折线图数据初始化
function polyLineInitDataByAdmin() {

    var temp = {
        startTimeStr: $("#startTm").val(),//
        endTimeStr: $("#endTm").val()
    }

    $.ajax({
        url: "/clueFollow/getAdminPolyLine",
        async: true,
        data: temp,
        type: "POST",
        dataType: "json",
        success: function (result) {
            if (result.code == "000000") {
                polyLineInit('polyLine', result.data);//折线图
            }
        },
        error: function (res) {
            alert('请求失败')
        }
    })
}

//总跟进次数饼状图数据初始化
function numPieInitDataByAdmin() {
    var temp = {
        startTimeStr: $("#startTm").val(),//
        endTimeStr: $("#endTm").val()
    }
    $.ajax({
        url: "/clueFollow/getAdminNumPieData",
        async: true,
        data: temp,
        type: "POST",
        dataType: "json",
        success: function (result) {
            if (result.code === "000000") {
                // var newArr = result.data.map(item => ({
                //     name: item.productName,
                //     value: item.proportion,
                // }))
                pieInit('numPie', '总跟进次数', result.data)//饼状图
            }
        },
        error: function (res) {
            alert('请求失败')
        }
    })
}

//状态值饼状图数据初始化
function statusPieInitDateByAdmin(type, index) {

    let url = '';
    //商机
    if (type === 'business') {
        url = '/clueFollow/getBusinessStatusData'
    } else if (type === 'process') {//过程
        url = '/clueFollow/getAdminProcessStatusData'
    }
    var temp = {
        type: 1,
        startTimeStr: $("#startTm").val(),//
        endTimeStr: $("#endTm").val()
    }

    //下标从0开始，对应跟进类型需+1
    temp.type = index + 1;
    $.ajax({
        url: url,
        async: true,
        data: temp,
        type: "POST",
        dataType: "json",
        success: function (result) {
            if (result.code === "000000") {
                pieInit('statusPie', '状态', result.data)//饼状图
            }
        },
        error: function (res) {
            alert('请求失败')
        }
    })
}

function followStatisticsByAdmin() {
//先销毁表格
    $dataInfo.bootstrapTable('destroy');
    $dataInfo.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/clueFollow/selectAdminClueFollowChartVOList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: false,//是否启用排序
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '', field: 'type', align: 'left', valign: 'middle'},
            {title: '会员产品跟进', field: 'member', align: 'left', valign: 'middle'},
            {title: '非会员产品跟进', field: 'nonMembers', align: 'left', valign: 'middle'},
            {title: '过程跟进', field: 'process', align: 'left', valign: 'middle', formatter: processStatusPieInitDate},
            {title: '商机跟进', field: 'business', align: 'left', valign: 'middle', formatter: businessStatusPieInitDate},
            {title: '总计', field: 'sum', align: 'left', valign: 'middle'}
        ],
        responseHandler: function (result) {
            if (result.code === "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            $('#followStatisticsTable tbody tr:first-child').addClass('active-row');
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

function processStatusPieInitDate(value, row, index) {
    return '<a href="JavaScript:void(0);" title="点击可查看过程状态饼状图" onclick=\'statusPieInitDateByAdmin(\"process",' + index + ')\'>' + value + '</a>';
}

function businessStatusPieInitDate(value, row, index) {
    return '<a href="JavaScript:void(0);" title="点击可查看商机状态饼状图" onclick=\'statusPieInitDateByAdmin(\"business",' + index + ')\'>' + value + '</a>';
}

/**
 * 查询参数
 */
function queryParams() {
    var param = {};
    //搜索条件
    param.dateUnit = $("#dateUnit").val();  //本周1 本月2 上月3
    param.startTimeStr = $("#startTm").val();  //开始时间
    param.endTimeStr = $("#endTm").val();  //结束时间
    return param;
}

/**
 * 本周/本月/上月切换
 * @param time
 */
function adminSearchByTime(time) {
    refresh();
}

function refresh() {
    $dataInfo.bootstrapTable('refreshOptions', {pageNumber: 1});
    polyLineInitDataByAdmin();//折线图数据初始化
    numPieInitDataByAdmin();//总跟进次数饼状图数据初始化
}

function searchByTime() {
    $("#dateUnit").val(0);
    refresh();
}

/**
 * 折线图初始化
 */
function polyLineInit(id, data) {
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);

    let option = {
        title: {
            text: ''
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: data.type,
            top: '16'
        },
        grid: {
            top: '80',
            left: '3%',
            right: '5%',
            bottom: '20',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            axisLine: {
                lineStyle: {
                    color: '#ddd'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#999999',
                padding: [8, 0, 0, 0]
            },
            data: data.time
        },
        yAxis: {
            type: 'value',
            minInterval: 1,
            axisLine: {
                lineStyle: {
                    color: '#ddd'
                }
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#999',
                padding: [0, 8, 0, 0]
            },
            splitLine: {
                show: true,
                lineStyle: {
                    color: '#f3f3f3',
                    type: 'dotted',
                    width: 1
                }
            }
        },
        color: [
            '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272'
        ],
        series: [
            {
                name: '线上电话',
                type: 'line',
                data: data.online
            },
            {
                name: '线下电话',
                type: 'line',
                data: data.offline
            },
            {
                name: '拜访',
                type: 'line',
                data: data.visit
            },
            {
                name: '微信',
                type: 'line',
                data: data.wecat
            },
            {
                name: '陪访',
                type: 'line',
                data: data.acvisit
            },
            {
                name: '邮件',
                type: 'line',
                data: data.mail
            }
        ]
    };

    myChart.setOption(option);
    window.addEventListener("resize", function () {
        myChart.resize();
    });
}


/**
 * 饼状图图初始化
 */
function pieInit(id, name, data) {
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);
    let option = {
        tooltip: {
            trigger: 'item'
        },
        legend: {
            top: '16',
            left: 'center'
        },
        color: [
            '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452'
        ],
        series: [
            {
                name: name,
                type: 'pie',
                avoidLabelOverlap: false,
                top: '50',
                bottom: '0',
                // center: [],
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'inner',
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '16',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: data
            }
        ]
    };
    myChart.setOption(option);
    window.addEventListener("resize", function () {
        myChart.resize();
    });

}